package com.huha.controller;

import com.huha.entity.DecryptedJdbc;
import com.huha.entity.JdbcRequest;
import com.huha.vo.DecryptedVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.huha.constant.EncAndDecConstant.SM4_QZ;
import static com.huha.constant.MessageConstant.ERROR_TEXT_INVALID_INPUT;

@Slf4j
@RestController
@RequestMapping("/api/encanddec")
public class EncAndDecController {

    @PostMapping("/decrypt")
    public DecryptedVO decrypt(@RequestBody JdbcRequest request) {
        log.info("执行jdbc字符串解密，jdbcString:{}", request.getJdbcString());
        String jdbcString = request.getJdbcString();
        DecryptedVO decryptedJdbc = parseJdbcString(jdbcString);
        return decryptedJdbc;
    }
    private DecryptedVO parseJdbcString(String jdbcString) {
        DecryptedVO decryptedJdbc = new DecryptedVO("");
        try {
            String url = "";
            String username = "";
            String password = "";
            StringBuilder stringBuilder = new StringBuilder();
            // 使用正则表达式解析连接字符串
            Pattern pattern = Pattern.compile("url=(.+)\nusername=(.+)\npassword=(.+)");
            Matcher matcher = pattern.matcher(jdbcString);
            if (matcher.find()) {
                url = matcher.group(1);
                username = matcher.group(2);
                password = matcher.group(3);

                if (url.contains(SM4_QZ)) {
                    url = com.epoint.ztb.api.client.token.SM4Util.decrypt(url.replace(SM4_QZ, ""));
                }
                if (username.contains(SM4_QZ)) {
                    username = com.epoint.ztb.api.client.token.SM4Util.decrypt(username.replace(SM4_QZ, ""));
                }
                if (password.contains(SM4_QZ)) {
                    password = com.epoint.ztb.api.client.token.SM4Util.decrypt(password.replace(SM4_QZ, ""));
                }

                stringBuilder.append("url=").append(url).append("\n");
                stringBuilder.append("username=").append(username).append("\n");
                stringBuilder.append("password=").append(password);
            } else {
                stringBuilder.append(ERROR_TEXT_INVALID_INPUT);
            }

            decryptedJdbc.setDecryptedJdbc(stringBuilder.toString());
            return decryptedJdbc;
        } catch (Exception e) {
            log.info("解密失败：" + e);
        }
        return null;
    }

}
